import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { Store } from '@ngxs/store';
import { SetUserInfoAction } from '../stores/auth/auth.action';
import { map } from 'rxjs/operators';
import { WebStorageService } from './webStorage.service';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    base = '/web/';
    constructor(private _http: HttpClient,
                private _store: Store,
                private webStorageService: WebStorageService) {}

    /**
     * 获取验证码
     */
    captchaImage():Observable<any>{
        return this._http.get(environment.baseUrl  + '/captchaImage');
    }

    /**
     * 登录验证
     */
    authLogin(queryParams: any): Observable<any> {
        return  this._http.post(environment.baseUrl  + '/login', queryParams).pipe(map((res: any) => {
            if (res.code === 200){
                this.webStorageService.setToken(res.token);
            }
            return res;
        }));
    }




    isLogin(){
        if (this.webStorageService.getToken() == null) {
            return false;
        }else {
            return true;
        }
    }


    /**
     * 用户注册
     */
    userRegister(queryParams: any): Observable<any> {
        return  this._http.post(environment.baseUrl + this.base + 'auth/userRegister', queryParams);
    }

    /**
     * 获取用户信息
     */
    getUserResume(): Observable<any> {
        if (this.webStorageService.getToken() != null){
            return this._http.get(environment.baseUrl  + '/getInfo').pipe( map((res: any) => {
                if ( res.success){
                    this._store.dispatch(new SetUserInfoAction(res.user.avatar)).subscribe();
                }
                return res;
            }));
        }else {
            return new Observable<any>();
        }
    }

    /**
     * 根据用户获取菜单
     */
    getUserMenu(): Observable<any> {
        return this._http.get(environment.baseUrl + '/getRouters');
    }

    /**
     * 退出登录
     */
    logOut(): Observable<any> {
        return this._http.post(environment.baseUrl + this.base + 'auth/loginOut', '');
    }
}
